package com.example.musicapp.presenter;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;

import com.example.musicapp.application.MyApp;
import com.example.musicapp.base.BasePresenter;
import com.example.musicapp.bean.Music;
import com.example.musicapp.contract.ISearchContract;
import com.example.musicapp.model.SearchModel;
import com.example.musicapp.network.HttpResponseListener;
import com.example.musicapp.storage.factory.DaoFactory;
import com.example.musicapp.utils.HttpUtils;
import com.example.musicapp.utils.ImageLoader;
import com.example.musicapp.view.SearchActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class SearchPresenter extends BasePresenter<SearchActivity> implements ISearchContract.ISearchPre {
    private static final int MESSAGE_HOT_SUCCESS = 101;
    private static final int MESSAGE_SEARCH_RESULT = 102;
    private ISearchContract.ISearchModel mSearchModel = new SearchModel();
    private List<String> mHotList = new ArrayList<>();
    private static String sMusicUri;
    private Handler mHandler = new MyHandler(this);

    private static class MyHandler extends Handler {

        private WeakReference<SearchPresenter> modelWeakReference;

        public MyHandler(SearchPresenter presenter) {
            modelWeakReference = new WeakReference<>(presenter);
        }

        @Override
        public void handleMessage(Message msg) {
            SearchPresenter presenter = modelWeakReference.get();
            if (presenter != null) {
                switch (msg.what) {
                    case MESSAGE_HOT_SUCCESS:
                        List<String> list = (List<String>) msg.obj;
                        if (presenter.getView()!=null) {
                            presenter.getView().getHotSuccess(list);
                        }
                        break;

                    case MESSAGE_SEARCH_RESULT:
                        if (presenter.getView() != null) {
                            presenter.getView().searchSuccess((List<Music>) msg.obj);
                        }
                        break;
                    default:
                        break;


                }
            }
        }
    }

    public SearchPresenter(SearchActivity view) {
        super(view);
    }

    @Override
    public int search(String searchThing, int curPage) {
        mSearchModel.search(searchThing, curPage,new HttpResponseListener() {
            @Override
            public void onSuccess(Object tag) throws JSONException {
                String data = (String) tag;


                JSONObject jsonObject = new JSONObject(data);
                JSONObject jsonObject1 = jsonObject.getJSONObject("result");
                JSONArray jsonArray = jsonObject1.getJSONArray("songs");
                List<Music> list = new ArrayList<>();
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                    long id = jsonObject2.getLong("id");
                    int duration = jsonObject2.getInt("dt");
                    String songName = jsonObject2.getString("name");
                    JSONObject  picJson = jsonObject2.getJSONObject("al");
                    String singerUri = picJson.getString("picUrl");
                    String picUri = singerUri+"?param=100y100";
                    String picUriHd = singerUri+ "?param=500y500";
//                    Bitmap bitmap = ImageLoader.build(MyApp.getContext()).loadBitmap(picUri,60,60);
                    JSONArray jsonArrayArtist = jsonObject2.getJSONArray("ar");
                    JSONObject jsonObjectSinger = jsonArrayArtist.getJSONObject(0);
                    String singer = jsonObjectSinger.getString("name");


                    String musicUrl = getMusicUri(id);


                    Music music = new Music();
                    music.setAlbum(picUri);
                    music.setAlbumHd(picUriHd);
                    music.setDuration(duration);
                    music.setId(id);
                    music.setPath(musicUrl);
                    music.setSong(songName);
                    music.setSinger(singer);
//

                    list.add(music);
                }
                Message message = mHandler.obtainMessage();
                message.what = MESSAGE_SEARCH_RESULT;
                message.obj = list;
                mHandler.sendMessage(message);

            }

            @Override
            public void onFailure(Object tag, Object failure) {
            }
        });
        return 0;
    }

    @Override
    public void addHistory(String word) {
        DaoFactory.getHistoryDao(MyApp.getContext()).insertRecord(word);
    }

    @Override
    public void getHotWord() {
        mSearchModel.requestHotWord(new HttpResponseListener() {
            @Override
            public void onSuccess(Object tag) throws JSONException {
                String response = (String) tag;
                JSONObject jsonObject = new JSONObject(response);
                int code = jsonObject.getInt("code");
                if (code == 200) {
                    JSONObject jsonObject1 = jsonObject.getJSONObject("result");
                    JSONArray jsonArray = jsonObject1.getJSONArray("hots");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                        String hot = jsonObject2.getString("first");

                        mHotList.add(hot);
                    }
                }
                Message message = mHandler.obtainMessage();
                message.what = MESSAGE_HOT_SUCCESS;
                message.obj = mHotList;
                mHandler.sendMessage(message);
            }

            @Override
            public void onFailure(Object tag, Object failure) {

            }
        });
    }


    private String getMusicUri(long id) {
        String url = "http://music.gochiusa.top/song/url?id=" + id;
        String musicUri = null;
        HttpUtils.sendHttpNoThread(url, new HttpResponseListener() {
            @Override
            public void onSuccess(Object tag) throws JSONException {
                JSONObject jsonObject = new JSONObject((String) tag);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                JSONObject jsonObject1 = jsonArray.getJSONObject(0);
                String url1 = jsonObject1.getString("url");
                sMusicUri = url1;
            }

            @Override
            public void onFailure(Object tag, Object failure) {

            }
        });


        return sMusicUri;
    }


}
